<?php

namespace App\Http\Controllers\V1\Admin;

use Illuminate\Http\Request;
use App\Models\V1\AdminUser;
use App\Models\V1\BasicFaculty;
use App\Models\V1\BasicStudent;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\V1\ProfileUpdateRequest;
use App\Http\Requests\V1\PasswordUpdateRequest;

class ProfileController extends Controller
{
    /**
     * 显示登录用户信息界面
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        // 获取登录用户
        $loginUser = Auth::user();

        // 获取登录用户基本信息
        $isStaff = $loginUser['is_staff'];
        $data['isStaff'] = $isStaff;
        $data['profileData'] = $this->getUserInfo($loginUser, $isStaff);

        return view('v1.profile', $data);
    }

    /**
     * 显示登录用户修改密码界面
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function password()
    {
        // 获取登录用户
        $loginUser = Auth::user();

        // 获取登录用户基本信息
        $isStaff = $loginUser['is_staff'];
        $data['isStaff'] = $isStaff;
        $data['profileData'] = $this->getBaseUserInfo($loginUser, $isStaff);

        return view('v1.password', $data);
    }

    /**
     * 更新用户基本信息
     *
     * @param  ProfileUpdateRequest $request
     * @return \Illuminate\Http\Response
     */
    public function update(ProfileUpdateRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '账号[' . $request->input('code') . '],更新个人信息失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateProfile($request);

            // 更新用户资料
            $successFlag = $this->handleProfile($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '账号[' . $request->input('code') . '],更新个人信息成功！';
            }
        }

        return $response;
    }

    /**
     * 更新用户密码信息
     *
     * @param Request $request
     * @return array
     */
    public function resetPassword(PasswordUpdateRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '账号[' . $request->input('code') . '],修改个人密码失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validatePassword($request);

            // 验证原密码是否正确
            $logRequest = [
                'code' => $request->input('code'),
                'password' => $request->input('password'),
            ];

            if (Auth::validate($logRequest)) {
                // 更新用户密码
                $successFlag = $this->handlePassword($request);

                if ($successFlag) {
                    $response['rspStatus'] = true;
                    $response['rspMsg'] = '账号[' . $request->input('code') . '],修改个人密码成功！';
                }
            } else {
                $response['rspMsg'] = '账号[' . $request->input('code') . '],原密码不正确！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 获取登录用户基本信息
     *
     * @param AdminUser $user
     * @param  int $flag
     * @return array
     */
    private function getUserInfo(AdminUser $user, $flag)
    {

        // 登录用户信息返回格式
        $loginData = array(
            'code' => '',
            'name' => '',
            'avatar' => '',
            'department' => '',
            'major' => '',
            'class' => '',
            'dorm' => '',
            'telephone' => '',
            'mobile' => '',
            'email' => '',
            'title' => '',
            'address' => '',
            'created_at' => '',
            'updated_at' => '',
        );

        if ($flag) {
            $staff = $user->faculty;
            if (!empty($staff)) {
                $department = $staff->department;
                $loginData['code'] = $staff['code'];
                $loginData['name'] = $staff['name'];
                $loginData['avatar'] = empty($staff['avatar'])?env('APP_URL').'/images/default.jpg':$staff['avatar'];
                $loginData['department'] = $department['name'];
                $loginData['telephone'] = $staff['telephone'];
                $loginData['mobile'] = $staff['mobile'];
                $loginData['email'] = $staff['email'];
                $loginData['title'] = $staff['title'];
                $loginData['created_at'] = $staff['created_at'];
                $loginData['updated_at'] = $staff['updated_at'];
            }
        } else {
            $student = $user->student;
            $class = $student->classes;
            $major = $class->major;
            $loginData['code'] = $student['code'];
            $loginData['name'] = $student['name'];
            $loginData['avatar'] = empty($student['avatar'])?env('APP_URL').'/images/default.jpg':$student['avatar'];
            $loginData['major'] = $major['name'];
            $loginData['class'] = $class['name'];
            $loginData['dorm'] = $student['dorm_code'];
            $loginData['mobile'] = $student['mobile'];
            $loginData['email'] = $student['email'];
            $loginData['address'] = $student['address'];
            $loginData['created_at'] = $student['created_at'];
            $loginData['updated_at'] = $student['updated_at'];
        }

        return $loginData;
    }

    private function getBaseUserInfo(AdminUser $user, $flag)
    {
        // 登录用户信息返回格式
        $loginData = array(
            'code' => '',
            'name' => '',
        );

        if ($flag) {
            $staff = $user->faculty;
            $loginData['code'] = $staff['code'];
            $loginData['name'] = $staff['name'];
        } else {
            $student = $user->student;
            $loginData['code'] = $student['code'];
            $loginData['name'] = $student['name'];
        }

        return $loginData;
    }

    ///////////////////////////////////////////////////////////////////
    /// 表单验证功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新用户资料验证请求
     *
     * @param Request $request
     */
    private function validateProfile(Request $request)
    {
        if ($request->method()==='POST') {
            $flag = $request->input('isStaff');
            $rules = $request->rules();
            if ($flag) {
                $rules['code'] = 'bail|required|exists:basic_faculties,code,deleted_at,NULL';
                $rules['mobile'] = 'bail|required|digits:11';
                if ($request->input("telephone") !== null) {
                    $rules['telephone'] = 'digits_between:7,8';
                }
                if ($request->input("email") !== null) {
                    $rules['email'] = 'email';
                }
            } else {
                $rules['code'] = 'bail|required|exists:basic_students,code,deleted_at,NULL';
                $rules['mobile'] = 'bail|required|digits:11';
                if ($request->input("email") !== null) {
                    $rules['email'] = 'email';
                }
            }
            $rules['captcha'] = 'bail|required|captcha';
            $messages = $request->messages();
            // 执行表单数据验证
            $this->validate($request, $rules, $messages);
        }
    }

    /**
     * 处理更新用户密码验证请求
     *
     * @param Request $request
     */
    private function validatePassword(Request $request)
    {
        if ($request->method()==='POST') {
            $rules = $request->rules();
            $rules['captcha'] = 'bail|required|captcha';
            $messages = $request->messages();
            // 执行表单数据验证
            $this->validate($request, $rules, $messages);
        }
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新个人资料
     *
     * @param Request $request
     * @return bool
     */
    private function handleProfile(Request $request)
    {
        $flag = $request->input('isStaff');
        $where = $request->input('code');
        $data['mobile'] = $request->input('mobile');
        if ($request->input("email") !==null) {
            $data['email'] = $request->input('email');
        }

        if ($flag) {
            if ($request->input("telephone") !== null) {
                $data['telephone'] = $request->input('telephone');
            }
            $rspObj = BasicFaculty::where('code',$where)->update($data);
        } else {
            if ($request->input("address") !== null) {
                $data['address'] = $request->input('address');
            }
            $rspObj = BasicStudent::where('code',$where)->update($data);
        }
        return $rspObj;
    }

    /**
     * 处理更新密码
     *
     * @param Request $request
     * @return bool
     */
    private function handlePassword(Request $request)
    {
        $where = $request->input('code');

        $data =[
            'password' => bcrypt($request->input('newpwd')),
        ];
        $rspObj = AdminUser::where('code',$where)->update($data);

        return $rspObj;
    }
}
